package core.collection.mymap;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
 * map集合的遍历
 *
 * @author
 * @create 2018-12-23 11:13
 **/
public class mymap_2_Map_Iterator {
    public static void main(String[] args){
        //demo_keySet();
        demo_entrySet();
    }


    /**
     * 通过查看Map集合的api发现没有iterator方法,那么双列集合如何迭代呢?
     * 根据键获取值
     */
    public static void demo_keySet(){
        Map<String, Integer> map = new HashMap<>();
        map.put("张三", 23);
        map.put("李四", 24);
        map.put("王五", 25);
        map.put("赵六", 26);

        /*Set<String> keySet = map.keySet();
        Iterator<String> it = keySet.iterator();
        while (it.hasNext()){
            String key = it.next();
            Integer value = map.get(key);
            System.out.println(key + "=" + value);
        }*/

        /**
         * 使用增强for循环遍历
         */
        for(String key:map.keySet()){
            System.out.println(key + "=" + map.get(key));
        }
    }

    /**
     * 根据键值对对象获取键和值
     */
    public static void demo_entrySet(){
        Map<String, Integer> map = new HashMap<>();
        map.put("张三", 23);
        map.put("李四", 24);
        map.put("王五", 25);
        map.put("赵六", 26);

        //Map.Entry说明Entry是Map的内部接口，将键和值封装成了内部对象
        /*Set<Map.Entry<String,Integer>> entrySet = map.entrySet();
        Iterator<Map.Entry<String,Integer>> it = entrySet.iterator();
        while (it.hasNext()){
            Map.Entry<String,Integer> en = it.next();
            System.out.println(en.getKey() + "=" +en.getValue());
        }*/

        //import java.util.Map
        //父类引用指向子类对象
        for(Map.Entry<String,Integer> en : map.entrySet()){
            System.out.println(en.getKey() + "=" + en.getValue());
        }

        //import java.util.Map.Entry  Entry是Map的静态内部类，实现了内部接口Map.Entry
        //直接获取子类对象
        for(Entry<String,Integer> en : map.entrySet()){
            System.out.println(en.getKey() + "=" + en.getValue());
        }
    }
}
